﻿using System.Web;
using CustomerAssistant.Core;
using CustomerAssistant.DAL;
using Itour.Models;
using System.IO;

namespace CustomerAssistantWebServer
{
    public class LoginClientHandle : IClientHandle
    {
        public IClientHandle NextNode
        {
            get;
            set;
        }

        public string RequestKey
        {
            get { return "login"; }
        }

        public void Response(HttpRequest Request, Stream OutputStream)
        {
            if (string.Compare(Request[Util.REQUEST_KEY], RequestKey, true) == 0)
            {
                var operationName = Request["oname"];
                var pwdHASH = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(Request["pwd"], "SHA1");
                OperatorLoginData info = new OperatorLoginData();
                info.OperatorName = operationName;
                info.Password = pwdHASH;
                ClientDB.Instance.Login(ref info);
                using (StreamWriter sw = new StreamWriter(OutputStream))
                {
                    if (info == null)
                        sw.Write(string.Empty);
                    else
                        sw.Write(info.ClientTypeID == 2 ? Util.Serialize<OperatorLoginData>(info) : null);
                    sw.Flush();
                }
            }
            else
            {
                if (NextNode != null)
                    NextNode.Response(Request, OutputStream);
            }
        }
    }
}